package com.kk.quyan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kk.quyan.entity.Label;
import com.kk.quyan.dao.LabelMapper;
import com.kk.quyan.entity.VO.LabelVO;
import com.kk.quyan.service.LabelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 标签表 服务实现类
 * </p>
 *
 * @author kk
 * @since 2020-11-21
 */
@Service
public class LabelServiceImpl extends ServiceImpl<LabelMapper, Label> implements LabelService {
    @Resource
    private LabelMapper labelMapper;

    //递归查找
    @Override
    public LabelVO buildLabelByLabelId(int labelId) {
        //查看该标签是否存在
        Label label = labelMapper.selectById(labelId);
        Assert.notNull(label,"标签不存在");

        LabelVO labelVO = new LabelVO();
        BeanUtil.copyProperties(label,labelVO);
        List<LabelVO> children = labelMapper.selectLabelChildren(labelId);
        if (children==null || children.size()==0){
            labelVO.setLeaf(true);
        }
        labelVO.setChildren(buildLabel(children));
        return labelVO;
    }

    private List<LabelVO> buildLabel(List<LabelVO> children) {
        for (LabelVO labelVO:children){
            //优化查询数量即可
            Integer count = labelMapper.selectCount(new QueryWrapper<Label>().eq("pid", labelVO.getId()));
            if (count==0){
                labelVO.setLeaf(true);
            }else{
                List<LabelVO> son = labelMapper.selectLabelChildren(labelVO.getId());
                labelVO.setChildren(buildLabel(son));
            }
        }
        return children;
    }
}
